package com.quarkus.resource;

import com.quarkus.entity.users.User;
import io.quarkus.hibernate.orm.PersistenceUnit;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.panache.common.Page;
import io.quarkus.panache.common.Sort;
import io.vertx.core.json.JsonObject;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.beans.BeanProperty;
import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2021/3/21 15:08
 * @description：
 */
@Path("user")
public class UserResource {


    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Object getUserById(@PathParam("id") Long id){
        return User.findById(id);
    }


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    public int save(User user){
        user.persist();
        return 1;
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional
    public User update(User user){

        User u = User.findById(user.id);

        u.setName(user.getName());

        return user;
    }


    @DELETE
    @Transactional
    @Path("{id}")
    public boolean delete(@PathParam("id") Long id){

        return User.deleteById(id);
    }

    @GET
    @Path("like/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> queryByListByNames(@PathParam("name") String name){
        return User.list("name like ?1", String.format("%%%s%%", name));
    }

    @PUT
    @Path("updateByQuery")
    @Transactional
    public int updateByQuery(@QueryParam("name") String name, @QueryParam("newName") String newName){
        return User.update("update t_user set name = ?1 where name like ?2", newName, String.format("%%%s%%", name));
    }

    @GET
    @Path("queryByPage")
    @Produces(MediaType.APPLICATION_JSON)
    public JsonObject queryByPage(@QueryParam("name") String name, @QueryParam("pageSize") Integer pageSize, @QueryParam("pageNum") Integer pageNum){
        PanacheQuery<User> query = User.find("name", Sort.ascending("id"), name);

        query.page(Page.of(pageNum, pageSize));


        JsonObject res = new JsonObject();

        res.put("code", 200);
        res.put("data", query.list());
        res.put("pages", query.pageCount());
        res.put("total", query.count());

        return res;
    }


}
